<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/19
 * Time: 8:41
 */
namespace app\admin\controller;

use app\admin\model\DepartmentModel;
use app\admin\model\MemberModel;
use app\admin\model\RoleModel;
use app\admin\model\OrderModel;
use think\Db;

class Statistics extends Base
{
    /**
     * 数据统计
     * 客户统计/订单统计/业务统计
     * 黄
     */
    public function memberStatis ()
    {
        if (request()->isAjax()) {
			$param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $where = [];
            if (!empty($param['name'])) {
                $where['name'] = ['like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['phone'])) {
                $where['phone'] = ['like', '%' . $param['phone'] . '%'];
            }

			if(!empty($param['timeLength'])){
                $time_step = $param['timeLength'] * 24 * 3600;
            }else{
                $time_step = 1 * 24 * 3600;
            }

            if (!empty($param['grade'])) {
                $where['grade'] = $param['grade'];
            }
            if (!empty($param['status'])) {
                $where['status'] = (int)$param['status'];
            }
            $where['delete_status'] = array('neq',2);
            $member = new MemberModel();
            // 搜人
            $staff = input('param.staff');
            $ids = DB::name('user')->where('real_name','like', '%'.$staff.'%')->column('id');
            $idArr =[];
            if(!empty(session('can_see')[0])){
                foreach (session('can_see') as $v){
                    foreach($ids as $va){
                        if($v['create_uid'] == $va){
                            array_push($idArr,$v['create_uid']);
                        }
                    }
                }
            }
            if($staff && empty($idArr)){
                $idArr =[-1];
            }
            // 搜部门
            $departId = input('param.depart_id');
            $departModel = new DepartmentModel();
            $roleModel = new RoleModel();
            $departIds = $departModel->getSonsByPid($departId);
            array_push($departIds,['id'=>$departId]);
            $roles = [];
            foreach ($departIds as $k => $v){
                if(DB::name('role')->where('department_id',$v['id'])->find()) {
                    $roles[$k] = $roleModel->getUsersByDepartId($v['id']);
                }
            }
            $users = [];
            foreach ($roles as $k => $v){
                foreach($v as $ke => $va){
                    array_push($users,$va);
                }
            }
            $users = array_merge(array_filter($users));

            $member->where(function($query)use($idArr){
                foreach($idArr as $v){
                    $query->whereOr('create_uid',$v);
                }
            });
            $member->where(function($query)use($users){
                foreach($users as $v){
                    $query->whereOr('create_uid',$v);
                }
            });
			$selectResult = $member->getMemberByWhere($where, $offset, $limit);
			$i = 0;
            foreach($selectResult as $key=>$vo){
                $vo['status'] = Db::name('member_attr')->where(['id'=>$vo['status']])->value('name');//状态
                //时间
                if(!empty($param['time'])){
                    $start_time = strtotime(explode(" - ",$param['time'])[0]." 00:00:00");
                    $end_time = strtotime(explode(" - ",$param['time'])[1]." 23:59:59");
                    if( strtotime($vo['time_K']) < $start_time || strtotime($vo['time_K']) > $end_time){
                        unset($selectResult[$key]);
						$i++;
                    }
                }else{
					$start_time = strtotime(date("Y-m-d")." 00:00:00");
					$end_time = strtotime(date("Y-m-d")."23:59:59");
                    if( (strtotime($vo['time_K']) < $start_time  || (strtotime($vo['time_K']) > $end_time) ) ){
                        unset($selectResult[$key]);
						$i++;
                    }
                }
            }
            $total = $member->getAllMember($where) - $i;  // 总数据
			// print_r($member->getAllMember($where));
            $return['total'] = $total;
            $return['rows'] = $selectResult;
            return json($return);
        }
        return $this->fetch();
    }
    public function ajaxStatis ()
    {
        if (request()->isAjax()) {
            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $where = [];
            if (!empty($param['name'])) {
                $where['name'] = ['like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['phone'])) {
                $where['phone'] = ['like', '%' . $param['phone'] . '%'];
            }

			if(!empty($param['timeLength'])){
                $time_step = $param['timeLength'] * 24 * 3600;
            }else{
                $time_step = 1 * 24 * 3600;
            }

            if (!empty($param['grade'])) {
                $where['grade'] = $param['grade'];
            }
            if (!empty($param['status'])) {
                $where['status'] = (int)$param['status'];
            }
            $where['delete_status'] = array('neq',2);
            $member = new MemberModel();
            // 搜人
            $staff = input('param.staff');
            $ids = DB::name('user')->where('real_name','like', '%'.$staff.'%')->column('id');
            $idArr =[];
            if(!empty(session('can_see')[0])){
                foreach (session('can_see') as $v){
                    foreach($ids as $va){
                        if($v['create_uid'] == $va){
                            array_push($idArr,$v['create_uid']);
                        }
                    }
                }
            }
            if($staff && empty($idArr)){
                $idArr =[-1];
            }
            // 搜部门
            $departId = input('param.depart_id');
            $departModel = new DepartmentModel();
            $roleModel = new RoleModel();
            $departIds = $departModel->getSonsByPid($departId);
            array_push($departIds,['id'=>$departId]);
            $roles = [];
            foreach ($departIds as $k => $v){
                if(DB::name('role')->where('department_id',$v['id'])->find()) {
                    $roles[$k] = $roleModel->getUsersByDepartId($v['id']);
                }
            }
            $users = [];
            foreach ($roles as $k => $v){
                foreach($v as $ke => $va){
                    array_push($users,$va);
                }
            }
            $users = array_merge(array_filter($users));

            $member->where(function($query)use($idArr){
                foreach($idArr as $v){
                    $query->whereOr('create_uid',$v);
                }
            });
            $member->where(function($query)use($users){
                foreach($users as $v){
                    $query->whereOr('create_uid',$v);
                }
            });
			$selectResult = $member->getMemberByWhere($where, $offset, $limit);
            //时间
            if(!empty($param['timeInterval'])){
                $start_time = strtotime(explode(" - ",$param['timeInterval'])[0]." 23:59:59");
                $end_time = strtotime(explode(" - ",$param['timeInterval'])[1]." 23:59:59");
            }else{
                $end_time = strtotime(date('Ymd',time())."235959");
                $start_time = strtotime(date('Ymd',strtotime("-1 months"))."235959");
            }
			$pointNum = ceil(($end_time - $start_time) / $time_step);
			$Xdata = [];
			$redData = [];
            $blueData = [];
            $greenData = [];
            $kingData = [];
			for($i=0;$i<=$pointNum;$i++){
				$a = $start_time + $i * $time_step;//第i个时间
				array_push($Xdata,date("Y-m-d",($a)));
				if($i==0){
					$where['time'] = array('between',[$start_time,$start_time - $time_step]);
				}else{
					$where['time'] = array('between',[$a,$a + $time_step]);
				}
				$redData['data'][$i] = 0;
				$blueData['data'][$i] = 0;
				$greenData['data'][$i] = 0;
				$kingData['data'][$i] = 0;
				foreach($selectResult as $key=>$vo){
					if($i==0){
						if(strtotime($vo['time']) >= $start_time - $time_step && strtotime($vo['time']) < $start_time && $vo['status']==6){
							$redData['data'][$i] += 1;
						}
						if(strtotime($vo['time']) >= $start_time - $time_step && strtotime($vo['time']) < $start_time && $vo['status']==7){
							$blueData['data'][$i] += 1;
						}
						if(strtotime($vo['time']) >= $start_time - $time_step && strtotime($vo['time']) < $start_time && $vo['status']==8){
							$greenData['data'][$i] += 1;
						}
						if(strtotime($vo['time']) >= $start_time - $time_step && strtotime($vo['time']) < $start_time && $vo['status']==9){
							$kingData['data'][$i] +=  1;
						}
					}else{
						if(strtotime($vo['time']) >= $a - $time_step && strtotime($vo['time']) < $a && $vo['status']==6){
							$redData['data'][$i] += 1;
						}
						if(strtotime($vo['time']) >= $a - $time_step && strtotime($vo['time']) < $a && $vo['status']==7){
							$blueData['data'][$i] += 1;
						}
						if(strtotime($vo['time']) >= $a - $time_step && strtotime($vo['time']) < $a && $vo['status']==8){
							$greenData['data'][$i] += 1;
						}
						if(strtotime($vo['time']) >= $a - $time_step && strtotime($vo['time']) < $a && $vo['status']==9){
							$kingData['data'][$i] += 1;
						}
					}
				}
			}
			$redData['name'] = "跟踪";
			$blueData['name'] = "成交";
			$greenData['name'] = "释放";
			$kingData['name'] = "公共";
            return ['code'=>1,'Xdata'=>$Xdata,'redData'=>$redData,'blueData'=>$blueData,'greenData'=>$greenData,'kingData'=>$kingData,'Msg'=>'图表加载成功'];
        }
    }
    /**
     * 业务统计
     * 选择时间内 录入订单
     * 选择时间内 订单款项
     */
    public function businStatis ()
    {
		$uid = session('id');
		if(request()->isAjax()){
			$param = input('param.');
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			//客户姓名
			if(!empty($param['stu_name'])){
				$where['stu_name'] = array('like','%'.$param['stu_name'].'%');
			}
			//时间
			if(!empty($param['c_time'])){
				$start_time = strtotime(explode(" - ",$param['c_time'])[0]." 235959");
				$end_time = strtotime(explode(" - ",$param['c_time'])[1]." 235959");
				$where['c_time'] = array('between',[$start_time,$end_time]);
			}else{
				$start_time = strtotime(date('Ymd',time())." 000000");
                $end_time = strtotime(date('Ymd',time())." 235959");
				$where['c_time'] = array('between',[$start_time,$end_time]);
			}

			$where['delete_status'] = array('neq',1);

			$order = new OrderModel();

			//所属咨询师(成交人员)
			if(!empty($param['depart_id']) || !empty($param['staff'])){
				// 搜人
				$staff = input('param.staff');
				$ids = DB::name('user')->where('real_name','like', '%'.$staff.'%')->column('id');
				$idArr =[];
				if(!empty(session('can_see')[0])){
					foreach (session('can_see') as $v){
						foreach($ids as $va){
							if($v['create_uid'] == $va){
								array_push($idArr,$v['create_uid']);
							}
						}
					}
				}
				if($staff && empty($idArr)){
					$idArr =[-1];
				}
				// 搜部门
				$departId = input('param.depart_id');
				$departModel = new DepartmentModel();
				$roleModel = new RoleModel();
				$departIds = $departModel->getSonsByPid($departId);
				array_push($departIds,['id'=>$departId]);
				$roles = [];
				foreach ($departIds as $k => $v){
					if(DB::name('role')->where('department_id',$v['id'])->find()) {
						$roles[$k] = $roleModel->getUsersByDepartId($v['id']);
					}
				}
				$users = [];
				foreach ($roles as $k => $v){
					foreach($v as $ke => $va){
						array_push($users,$va);
					}
				}
				$users = array_merge(array_filter($users));
				$usersArr = [];
				if(!empty(session('can_see')[0])){
					foreach (session('can_see') as $v){
						foreach($users as $va){
							if($v['create_uid'] == $va){
								array_push($usersArr,$v['create_uid']);
							}
						}
					}
				}
				if($departId && empty($usersArr)){
					$usersArr =[-1];
				}

				$order->where(function($query)use($idArr){
					foreach($idArr as $v){
						$query->whereOr('consultant',$v);
					}
				});
				$order->where(function($query)use($usersArr){
					foreach($usersArr as $v){
						$query->whereOr('consultant',$v);
					}
				});

			}else{
				$where['consultant'] = $uid;
			}

			$orderArr = $order->getMyOrder($where, $offset, $limit);
			foreach ($orderArr as $key=>&$value){
				$u_id = $value['m_id'];
				$grade = $value['grade'];//层次
				$payment_method  = $value['payment_method'];//缴费方式
				$consultant = $value['consultant'];
				$mem_phone = Db::name('member')->where(['id'=>$u_id])->value('phone');//查询当前订单的客户信息
				$gradeN = Db::name('product_attr')->where(['id'=>$grade])->value('name');//获取当前层次
				$payment_methodN = Db::name('product_attr')->where(['id'=>$payment_method])->value('name');
				$consultantN = Db::name('user')->where('id',$consultant)->value('real_name');
				$value['phone'] = $mem_phone;
				$value['gradeN'] = $gradeN;
				$value['payment_methodN'] = $payment_methodN;
				$value['consultantN'] = $consultantN;
				$value['c_time'] = date('Y-m-d',$value['c_time']);
			}

			// $member = new MemberModel();
			// $member->where(function($query)use($idArr){
			//    foreach($idArr as $v){
			// 	   $query->whereOr('create_uid',$v);
			//    }
			// });
			// $member->where(function($query)use($users){
			//    foreach($users as $v){
			// 	   $query->whereOr('create_uid',$v);
			//    }
			// });
			$return['total'] = $order->getAllOrder($where);  // 总数据
			$return['rows'] = $orderArr;
			$return['sum'] = 0;
			foreach($return['rows'] as $val){
				//增加总金额
				$return['sum'] += $val['total_amount'];
			}
			return json($return);
		}
		return $this->fetch();
    }
	//业务业绩图表
    public function ajaxBusinStatis ()
    {
        if(request()->isAjax()){
            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $where = [];
            //客户姓名
            if(!empty($param['stu_name'])){
                $where['stu_name'] = array('like','%'.$param['stu_name'].'%');
            }
            //时间
            if(!empty($param['timeInterval'])){
                $start_time = strtotime(explode(" - ",$param['timeInterval'])[0]." 235959");
                $end_time = strtotime(explode(" - ",$param['timeInterval'])[1]." 235959");
                $where['c_time'] = array('between',[$start_time,$end_time]);
            }else{
                $start_time = strtotime(date('Ymd',strtotime("-1 months"))." 235959");
                $end_time = strtotime(date('Ymd',time())." 235959");
                $where['c_time'] = array('between',[$start_time,$end_time]);
            }
            $where['delete_status'] = array('neq',1);
            // 时间(步长)
            if(!empty($param['timeLength'])){
                $timeLength = $param['timeLength'] * 24 * 3600;
            }else{
                $timeLength = 1 * 24 * 3600;
            }

            $order = new OrderModel();

            //所属咨询师(成交人员)
            if(!empty($param['depart_id']) || !empty($param['staff'])){
                // 搜人
                $staff = input('param.staff');
                $ids = DB::name('user')->where('real_name','like', '%'.$staff.'%')->column('id');
                $idArr =[];
                if(!empty(session('can_see')[0])){
                    foreach (session('can_see') as $v){
                        foreach($ids as $va){
                            if($v['create_uid'] == $va){
                                array_push($idArr,$v['create_uid']);
                            }
                        }
                    }
                }
                if($staff && empty($idArr)){
                    $idArr =[-1];
                }
                // 搜部门
                $departId = input('param.depart_id');
                $departModel = new DepartmentModel();
                $roleModel = new RoleModel();
                $departIds = $departModel->getSonsByPid($departId);
                array_push($departIds,['id'=>$departId]);
                $roles = [];
                foreach ($departIds as $k => $v){
                    if(DB::name('role')->where('department_id',$v['id'])->find()) {
                        $roles[$k] = $roleModel->getUsersByDepartId($v['id']);
                    }
                }
                $users = [];
                foreach ($roles as $k => $v){
                    foreach($v as $ke => $va){
                        array_push($users,$va);
                    }
                }
                $users = array_merge(array_filter($users));
                $usersArr = [];
                if(!empty(session('can_see')[0])){
                    foreach (session('can_see') as $v){
                        foreach($users as $va){
                            if($v['create_uid'] == $va){
                                array_push($usersArr,$v['create_uid']);
                            }
                        }
                    }
                }
                if($departId && empty($usersArr)){
                    $usersArr =[-1];
                }

                $order->where(function($query)use($idArr){
                    foreach($idArr as $v){
                        $query->whereOr('consultant',$v);
                    }
                });
                $order->where(function($query)use($usersArr){
                    foreach($usersArr as $v){
                        $query->whereOr('consultant',$v);
                    }
                });

            }else{
                $where['consultant'] = session('id');
            }

            $orderArr = $order->getMyOrder($where, $offset, $limit);

            $Xdata = [];
            $kingData = [];
            $timeSutp = ceil($end_time - $start_time) / $timeLength;
            for ($i = 0; $i <= $timeSutp; $i++){
                $Ktime = $start_time + $i * $timeLength;
                array_push($Xdata,date('Y-m-d',$Ktime));
                $kingData['data'][$i] = 0;
                foreach ($orderArr as $key => $val){
                    if($i == 0){
                        if($val['c_time'] >= ($start_time - $timeLength) && $val['c_time'] < $start_time){
                            $kingData['data'][$i] += $val['total_amount'];
                        }
                    }else{
                        if($val['c_time'] >= ($Ktime - $timeLength) && $val['c_time'] < $Ktime){
                            $kingData['data'][$i] += $val['total_amount'];
                        }
                    }
                }
            }
            $kingData['name'] = '总业绩';
            return  ['code'=>1,'Xdata'=>$Xdata,'kingData' => $kingData,'Msg'=>'图表加载成功'];
        }
    }
}
